package com.hhuhh.smarthome.socket.support;

import org.apache.mina.core.buffer.IoBuffer;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.filter.codec.ProtocolDecoderAdapter;
import org.apache.mina.filter.codec.ProtocolDecoderOutput;

public class ByteDecoder extends ProtocolDecoderAdapter {

	private IoBuffer buff = IoBuffer.allocate(64).setAutoExpand(true);
	
	@Override
	public void decode(IoSession session, IoBuffer in, ProtocolDecoderOutput out)
			throws Exception {
		
		byte previous = 0;
		while (in.hasRemaining()) {
            byte current = in.get();

            if (previous == '\r' && current == '\n') {
                buff.flip();

                byte[] bytes = new byte[buff.limit()-1];
                
                buff.get(bytes);

                buff = IoBuffer.allocate(64).setAutoExpand(true);

                // 如果结束了，就写入转码后的数据
                out.write(bytes);
            }else {
                buff.put(current);
            }

            previous = current;
        }
	}

}


